<template>
  <Dialog v-model="show" @confirm="handleSubmit" :title="t('powerGroup.权限授权')" width="500">
    <div class="h-500 overflow-y-auto">
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="menuTree"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        default-expand-all
        :check-strictly="false"
        v-loading="loading"
      />
    </div>
  </Dialog>
</template>
<script setup>
import { ref, watch, onMounted } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";

const { t, locale } = useI18n();
const show = defineModel();
const emit = defineEmits(["success"]);
const treeRef = ref();
const menuTree = ref([]);
const loading = ref(false);
const defaultProps = ref({
  children: "children",
  label: "title" + locale.value,
});

watch(
  () => locale.value,
  () => {
    defaultProps.value.label = "title" + locale.value;
  }
);

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 获取菜单树
const getMenuTree = async () => {
  try {
    const res = await Api.getMenuTree();
    if (res.status === 200) {
      menuTree.value = res.data || [];
    }
  } catch (error) {
    console.error(t('powerGroup.获取菜单树失败'), error);
  }
};

// 获取角色菜单权限
const getRoleMenus = async (roleId) => {
  const res = await Api.getRoleInfo(roleId);
  const arr = res?.data?.menus?.map((item) => item.id) || [];
  arr.forEach(el=>{
    treeRef.value.setChecked(el, true, false)
  })
};

watch(show, async (val) => {
  if (val && props.data) {
    loading.value = true;
    await getMenuTree();
    await getRoleMenus(props.data.id);
    loading.value = false;
  }
});

// 提交权限设置
const handleSubmit = async () => {
  try {
    const checkedNodes = treeRef.value.getCheckedNodes();
    const halfCheckedNodes = treeRef.value.getHalfCheckedNodes();
    const menuIds = [...checkedNodes, ...halfCheckedNodes].map((node) => ({
      id: node.id,
    }));

    await Api.updateRoleMenu({
      id: props.data.id,
      menus: menuIds,
    });

    ElMessage.success(t('powerGroup.授权成功'));
    emit("success");
    show.value = false;
  } catch (error) {
    ElMessage.error(t('powerGroup.授权失败'));
  }
};

onMounted(() => {
  getMenuTree();
});
</script>
<style lang="scss" scoped>
.h-500 {
  height: 360px;
}
</style>
